<script setup>
import { inject, ref } from "vue";
import stepsview from "../components/steps/steps.vue";
import wxicon from "@/static/cloudlibrary/icon_weixin.png";
import yeicon from "@/static/cloudlibrary/icon_yue.png";
import dficon from "@/static/cloudlibrary/icon_daifu.png";
import dhicon from "./static/icom55.png";
import xxicon from "./static/icon44.png";
import { useCounterStore } from "@/stores/upgrade";
import { useaddressStore } from "@/stores/address";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { addressListApi } from "@/services/address";

import {
  upgradelist,
  upgradeorder,
  upPageApi,
  upgradePay,
} from "@/services/upfrade";
import { orderpay } from "@/services/pay";
import { mine, isPayPassApi, checkPayPass } from "@/services/user";
import { formatPrice } from "@/utils/formatPrice";
const dateobj = useCounterStore();

const date2obj = useaddressStore();

const price = ref(0);
const balance = ref(0);
const payid = ref("");
const payleveltype = ref(0);
const order_id = ref("");
const type = ref("");
const paylist = ref([
  {
    title: "收款码",
    des: "微信支付（推荐）",
    icon: wxicon,
    type: 1,
  },
  {
    title: "银行卡",
    des: "余额支付",
    icon: yeicon,
    type: 2,
  },
  // {
  //   title: "微信",
  //   des: "他人代付",
  //   icon: dficon,
  //   type: 3,
  // },
  // {
  //   title: "微信",
  //   des: "身份兑换码",
  //   icon: dhicon,
  //   type: 4,
  // },
  {
    title: "微信",
    des: "线下缴费",
    icon: xxicon,
    type: 5,
  },
  {
    title: "微信",
    des: "身份兑换码",
    icon: dhicon,
    type: 6,
  },
]);

const addressobj = ref({});
const verify_code = ref("");
const verify_code_pass = ref("");
onLoad((e) => {
  if (e.id) {
    payid.value = e.id;
    payleveltype.value = e.level_id ? 1 : 2;
  } else {
  }
  type.value = e.type ? e.type : "";
  upPageApifun(e.id, e.level_id ? 1 : 2);
  if (e.type == 2) {
    paylist.value.forEach((item, index) => {
      if (item.type == 4) {
        paylist.value.splice(index, 1);
      }
    });
  }
  // paytype.value = balance.value < price.value ? 1 : 2;
});

onShow(() => {
  if (date2obj.address) {
    addressobj.value = JSON.parse(date2obj.address);
    // form.value.address_id = addressobj.value.address_id;
  }

  isPayPassFun();
  setTimeout(() => {
    // paytype.value = balance.value < price.value ? 1 : 2;
  }, 300);
});

const current = ref(2);
const paytype = ref(2);
addressListFun();
async function addressListFun() {
  //发送请求
  let res = await addressListApi({ page: 1 });
  // addressData.value = res.data;
  if (res.data.list.length > 0) {
    res.data.list.forEach((item) => {
      if (item.is_default == 1) {
        addressobj.value = item;
      }
    });
  }
}

//地址
function addressListfun() {
  if ((addressobj.value && !addressobj.value.real_name) || !addressobj.value) {
    uni.navigateTo({
      url: "/pages/address_add/index?type=addup",
    });
  }
}
const goselectaddressfun = () => {
  uni.navigateTo({
    url: "/pages/address/index?type=addup",
  });
};

async function upgradeorderfun(id, type) {
  if (!addressobj.value.address_id) {
    return uni.$u.toast("请选择地址");
  }
  try {
    let res = await upgradeorder({
      id: id,
      type: type,
    });
    price.value = res.data.price;
    balance.value = res.data.balance;
    order_id.value = res.data.order_id;
  } catch (e) {
    uni.$u.toast(e.info);
    setTimeout(() => {
      uni.reLaunch({
        url: "/pages/upgrade/identitylv",
      });
    }, 1500);
  }
}

async function upPageApifun(id, type) {
  try {
    let res = await upPageApi({ id: id, type: type });
    price.value = res.data.price;
    balance.value = res.data.balance;
    if (balance.value < price.value) {
      paytype.value = 1;
    }
  } catch (e) {
    uni.$u.toast(e.info);
    setTimeout(() => {
      uni.reLaunch({
        url: "/pages/upgrade/identitylv",
      });
    }, 1500);
  }
}

function onBridgeReady(yishen, id) {
  WeixinJSBridge.invoke("getBrandWCPayRequest", yishen, (res) => {
    if (res) {
      uni.redirectTo({
        url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
      });

      // 使用以上方式判断前端返回,微信团队郑重提示：
      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
    }
  });
}

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const showPassword = ref(false);
const pay_pass = ref("");
const gopassword = async () => {
  if (!addressobj.value.address_id) {
    return uni.$u.toast("请选择地址");
  }
  if (paytype.value == 2 && balance.value < price.value) {
    uni.showToast({
      title: "余额不足，无法支付",
      icon: "none",
    });
    return;
  }

  if (paytype.value == 2 && isPayPass.value != 0) {
    showPassword.value = true;
    pay_pass.value = "";
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
  } else if (paytype.value == 2 && isPayPass.value == 0) {
    uni.showToast({
      title: "没有支付密码，前往设置",
      icon: "none",
    });

    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
      });
    }, 500);
  }
  if (
    paytype.value == "1" ||
    paytype.value == "3" ||
    paytype.value == "5" ||
    paytype.value == "6"
  ) {
    try {
      let res1 = await upgradeorder({
        id: payid.value,
        type: payleveltype.value,
        address_id: addressobj.value.address_id,
      });
      if (res1.code == 200) {
        price.value = res1.data.price;
        balance.value = res1.data.balance;
        order_id.value = res1.data.order_id;
      } else {
        uni.$u.toast(res1.info);
        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/upgrade/identitylv",
          });
        }, 1500);

        return;
      }
    } catch (e) {
      uni.$u.toast(e.info);
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/upgrade/identitylv",
        });
      }, 1500);
      return;
    }

    gepaymentfun();
  }

  if (paytype.value == "4") {
    uni.navigateTo({
      url: "/pages/upgrade/exchangeCode",
    });
  }
};

const gocancle = () => {
  showPassword.value = false;
  pay_pass.value = "";
};

const gepaymenttwofun = async () => {
  if (paytype.value == 2) {
    if (!pay_pass.value) {
      uni.showToast({
        title: "支付密码不能为空",
        icon: "none",
      });
      return;
    }
  }
  gepaymentfun();
};
const ispay = ref(false);
const gepaymentfun = async () => {
  let res = null;
  if (paytype.value == 2) {
    if (!pay_pass.value) {
      uni.showToast({
        title: "支付密码不能为空",
        icon: "none",
      });
      return;
    }

    // await upgradeorderfun(payid.value, payleveltype.value);

    // let ress2 = await upgradeorder({
    //   id: payid.value,
    //   type: payleveltype.value,
    // });
    // price.value = ress2.data.price;
    // balance.value = ress2.data.balance;
    // order_id.value = ress2.data.order_id;

    try {
      // 防止小程序输入密码重复支付
      if (!ispay.value) {
        ispay.value = true;
      } else {
        return;
      }
      if (!addressobj.value.address_id) {
        return uni.$u.toast("请选择地址");
      }
      let res1 = await upgradeorder({
        id: payid.value,
        type: payleveltype.value,
        address_id: addressobj.value.address_id,
      });
      if (res1.code == 200) {
        price.value = res1.data.price;
        balance.value = res1.data.balance;
        order_id.value = res1.data.order_id;
      } else {
        uni.$u.toast(res1.info);

        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/upgrade/identitylv",
          });
        }, 1500);
        return;
      }
    } catch (e) {
      uni.$u.toast(e.info);
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/upgrade/identitylv",
        });
      }, 1500);
      return;
    }

    try {
      res = await orderpay({
        order_id: order_id.value,
        pay_type: 1,
        pay_pass: pay_pass.value,
      });
    } catch (e) {
      uni.$u.toast(e.info);
      uni.reLaunch({
        url: "/pages/upgrade/upgradestate?type=2",
      });
    }

    if (res.code == 200) {
      uni.showToast({
        title: "支付成功",
        icon: "none",
      });
      uni.reLaunch({
        url: "/pages/upgrade/upgradestate?type=1",
      });
      dateobj.setformdate({});
      focusinput.value = false;
    } else {
      uni.showToast({
        title: res.info,
        icon: "none",
      });
      uni.reLaunch({
        url: "/pages/upgrade/upgradestate?type=2",
      });
    }
  } else if (paytype.value == 1) {
    let res = null;
    let yishen = null;
    try {
      // #ifdef H5
      res = await orderpay({ order_id: order_id.value, pay_type: 2 });
      yishen = JSON.parse(res.data.wxWcPayData);

      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            onBridgeReady(yishen, order_id.value),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent(
            "WeixinJSBridgeReady",
            onBridgeReady(yishen, order_id.value)
          );
          document.attachEvent(
            "onWeixinJSBridgeReady",
            onBridgeReady(yishen, order_id.value)
          );
        }
      } else {
        onBridgeReady(yishen, order_id.value);
      }
      // #endif

      // #ifdef MP-WEIXIN

      res = await orderpay({ order_id: order_id.value, pay_type: 3 });
      // yishen = JSON.parse(res.data.wxWcPayData);
      yishen = res.data;
      if (res.code == 200) {
        // 仅作为示例，非真实参数信息。
        uni.requestPayment({
          provider: "wxpay",
          timeStamp: yishen.timeStamp,
          nonceStr: yishen.nonceStr,
          package: yishen.package,
          signType: yishen.signType,
          paySign: yishen.paySign,
          success: function (res) {
            uni.reLaunch({
              url: "/pages/upgrade/upgradestate?type=1",
            });
          },
          fail: function (err) {
            uni.reLaunch({
              url: "/pages/upgrade/upgradestate?type=2",
            });
          },
        });
      } else {
        uni.reLaunch({
          url: "/pages/upgrade/upgradestate?type=2",
        });
      }

      // #endif
    } catch (e) {
      uni.showToast({
        title: e.info,
        icon: "none",
      });
    }

    return;

    uni.redirectTo({
      url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
    });
  } else if (paytype.value == 6) {
    try {
      res = await upgradePay({
        order_id: order_id.value,
        verify_code: verify_code.value + verify_code_pass.value,
      });
      console.log(res.code);
      if (res.code == 200) {
        // 仅作为示例，非真实参数信息。

        uni.reLaunch({
          url: "/pages/upgrade/upgradestate?type=1",
        });
      } else {
        uni.reLaunch({
          url: "/pages/upgrade/upgradestate?type=2",
        });
      }
    } catch (e) {
      uni.showToast({
        title: e.info,
        icon: "none",
      });
      uni.reLaunch({
        url: "/pages/upgrade/upgradestate?type=2",
      });
    }
    // uni.redirectTo({
    //   url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
    // });
  } else if (paytype.value == 3) {
    // uni.redirectTo({
    //   url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
    // });
    uni.navigateTo({
      url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
    });
  } else if (paytype.value == 5) {
    uni.navigateTo({
      url: `/pages/upgrade/offline_pay?order_id=${order_id.value}&price=${price.value}`,
    });
  } else {
    uni.showToast({
      title: "暂未开放",
      icon: "none",
    });
  }
};
const lastfun = () => {
  let pages = getCurrentPages();

  // 获取页面栈的长度，即页面跳转层级
  let level = pages.length;
  if (level > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({
      url: "/pages/index/index",
    });
  }
};

const selsectpaytype = (e) => {
  if (balance.value < price.value && e == 2) {
    uni.showToast({
      title: "余额不足",
      icon: "none",
    });
    return;
  }
  paytype.value = e;
};

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      gepaymentfun();
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};

const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
  });
};

const focusinput = ref(false);

const close = () => {
  showPassword.value = false;
  pay_pass.value = "";
  focusinput.value = false;
};
</script>

<template>
  <view class="upgrade">
    <stepsview :current="current"></stepsview>

    <view class="user-address">
      <view
        class="address-info-k"
        v-if="addressobj && addressobj.real_name"
        @click="goselectaddressfun"
      >
        <view class="address-info">
          <view class="address-info-name"
            ><text class="name">{{ addressobj.real_name }}</text
            ><text>{{ addressobj.phone }}</text></view
          >

          <view class="address-info-detail"
            >收货地址：{{
              addressobj.province +
              addressobj.city +
              addressobj.district +
              addressobj.detail
            }}</view
          >
        </view>
        <view>
          <up-icon name="arrow-right" color="#8C8C8C" size="32rpx"></up-icon>
        </view>
      </view>
      <view
        class="select-address"
        v-if="(addressobj && !addressobj.real_name) || !addressobj"
        @click="addressListfun"
      >
        <view class="select-address-add">
          <up-icon name="plus-circle" color="#F3498B " size="24"></up-icon>
        </view>

        <view class="add-text">添加收货地址</view>
      </view>
    </view>

    <view class="content-num">¥{{ formatPrice(price) }}</view>
    <view class="content-det" v-if="false">
      <view class="det-title">收款码缴费详情</view>
      <view class="det-des">
        <view class="det-left">订单信息</view>
        <view class="det-right">
          <text class="text-name">明松旺店主升级大礼包</text>
          <text class="text-see">查看</text>
        </view>
      </view>
      <view class="det-des">
        <view class="det-left">收款方</view>
        <view class="det-right"> 测试 </view>
      </view>
      <view class="det-des">
        <view class="det-left">升级人</view>
        <view class="det-right"> 测试 </view>
      </view>
      <view class="det-des">
        <view class="det-left">手机号</view>
        <view class="det-right"> 测试 </view>
      </view>
    </view>

    <view class="content-pay">
      <view
        class="content-pay-item"
        v-for="(item, index) in paylist"
        :key="index"
        @click="selsectpaytype(item.type)"
      >
        <view
          :class="
            balance < price && item.type == 2
              ? 'content-pay-left noselect'
              : 'content-pay-left'
          "
        >
          <image :src="item.icon" mode="widthFix" />
          <text>{{ item.des }}</text>
          <text v-if="item.type == 2">(可用{{ formatPrice(balance) }}元)</text>
        </view>
        <view class="content-pay-right" v-if="paytype == item.type">
          <image src="@/static/upgrade/select.png" mode="widthFix" />
        </view>
      </view>
      <view class="paytype-nums" v-if="paytype == 6"
        ><input
          type="text"
          placeholder="请输入身份兑换码"
          v-model="verify_code"
      /></view>
      <view class="paytype-nums" v-if="paytype == 6"
        ><input
          type="text"
          placeholder="请输入兑换码密码"
          v-model="verify_code_pass"
      /></view>
      <view style="width: 100%; height: 20rpx" v-if="paytype == 6"></view>
    </view>
  </view>

  <view class="foodr-bt">
    <view class="bt-next" @click="lastfun">上一步</view>
    <view class="bt-sbuit" @click="gopassword">立即支付</view>
  </view>

  <!-- 密码弹框 -->
  <view class="password_show">
    <u-popup
      :show="showPassword"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="password">
        <view class="popup-content-title">支付密码</view>
        <u-code-input
          v-model="pay_pass"
          :maxlength="6"
          dot
          size="80"
          @change="onChange"
          @finish="finish"
          :focus="focusinput"
        ></u-code-input>
        <view class="footer">
          <view class="closefun" @click="showPassword = false">取消</view>
          <view class="forgot" @click="forgot">忘记密码？</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<style lang="scss" scoped>
@import "./upgradepay.scss";
</style>
